<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @row-click="rowClick"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :before-close="beforeClose"
    >
      <!-- <div class="informationLabel el-tabs el-tabs--top el-tabs--border-card"></div> -->
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.systemCustomAttribute_delete" @click="handleDelete">删 除</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="isOnlinePrint">
        <el-tag :class="row.isOnlinePrint ? 'successTag' : 'dangerTag'">{{ row.isOnlinePrint === false ? '否' : '是' }}</el-tag>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import { getAttributeConfig, getAttributeConfigById, addAttributeConfig, removeAttributeConfig } from '@/api/system/custom-attribute-config';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'SYSTEM_CUSTOM_ATTRIBUTE',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timer: new Date().getTime(),
      selectionList: [],
      packingQuantity: '',
      option: {
        height: 'calc(100vh - 450px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        labelWidth: 130,
        highlightCurrentRow: true, // 选中高亮
        viewBtn: true,
        columnBtn: false,
        column: [
          {
            label: '名称',
            prop: 'lableCnName',
            width: 150,
            search: true,
            rules: [
              {
                required: true,
                message: '请选择名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'attributeKey',
            search: true,
            rules: [
              {
                required: true,
                message: '请选择编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datetime'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: true
          },
          // {
          //   label: '是否显示在列表',
          //   prop: 'isShowed',
          //   type: 'switch',
          //   dicData: [
          //     {
          //       label: '否',
          //       value: false
          //     },
          //     {
          //       label: '是',
          //       value: true
          //     }
          //   ],
          //   value: false
          // },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.systemCustomAttribute_add, false),
        delBtn: this.vaildData(this.permission.systemCustomAttribute_delete, false),
        editBtn: this.vaildData(this.permission.systemCustomAttribute_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    detailIds() {
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      addAttributeConfig(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      console.log(row);
      addAttributeConfig(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeAttributeConfig(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeAttributeConfig(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getAttributeConfigById(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
      this.rowClick(list[len]);
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getAttributeConfig(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.detailOption.addBtn = false;
        this.detailData = [];
        this.selectionDetailClear();
      });
    },
    /**
     * 单击事件
     */
    rowClick(row) {
      this.detailConfigId = row.id;
      this.packingName = row.name;
      this.detailOption.addBtn = true;
      this.onDetailLoad();
    },
    /**
     * 查询包装配置详情
     */
    onDetailLoad() {
      this.detailLoading = true;
      getAttributeConfigDetail(this.detailConfigId).then((res) => {
        const data = res.data.data;
        this.detailData = data;
        // this.$set(this.detailData ,)
        this.detailLoading = false;
        this.selectionDetailClear();
      });
    },
    detailRefreshChange() {
      this.onDetailLoad();
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionDetailClear() {
      this.selectionDetailList = [];
      this.$refs.detailCrud.toggleSelection();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}

.custom-informationLabel {
  .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
